
from fastapi import APIRouter,Depends,Request, HTTPException
from sqlalchemy.orm import Session
from pydantic import BaseModel
from jose import jwt, JWTError
from datetime import datetime, timedelta, timezone

from database import SessionLocal,get_db
from models.user_models import Patient,Account
import config
from services.auth_service import verify_token
from typing import Optional

from services.password_service import verify_password
from services.user_service import get_user

router = APIRouter()

SECRET_KEY = config.SECRET_KEY
ALGORITHM = config.ALGORITHM


from models.user_models import UserType
# 登录请求体模型
class LoginRequest(BaseModel):
    username: str
    password: str
    user_type: UserType


# 登录接口
@router.post("/login")
def login(data: LoginRequest, db: Session = Depends(get_db)):

    # print('username=%s pw=%s' % (data.username, data.password))
    try:
        account = db.query(Account).filter(Account.username == data.username).first()
    except ValueError:
        raise HTTPException(status_code=400, detail="Invalid ID format")

    # 检查账户是否存在
    if account is None:
        raise HTTPException(status_code=401, detail="User not found")

    # 验证密码是否正确
    if not verify_password(data.password, account.password_hash):
    # if account.password != data.password:
        raise HTTPException(status_code=401, detail="Invalid username or password")

    user=get_user(account.user_type,db,account.user_ref_id)

    payload = {
        "sub": str(account.ID), #用户id
        "exp": datetime.now(timezone.utc) + timedelta(hours=8), #过期时间8小时
        "user_ref_id": account.user_ref_id,
        "user_type":account.user_type.value #用户类型枚举
    }
    token = jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
    #
    return {"access_token": token, "token_type": "bearer", "user_type": account.user_type.to_str(),"user": user.to_dict()}



# token 测试接口
@router.get("/token_test")
def token_test(token: str, db: Session = Depends(get_db)):
    user = verify_token(token, db)
    return {"account_ID": user.ID, "name": user.name ,"user_type":user.user_type}


